package com.atguigu.cloud.config.Filter;/**
 * @Auter 李孝在
 * @Date 2024/11/19
 */

import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


/**
 * @projectName: keshe
 * @package: com.atguigu.cloud.config.interceptor
 * @className: RequestInterceptor
 * @author: Eric
 * @description: TODO
 * @date: 2024/11/19 01:44
 * @version: 1.0
 */


@Configuration
public class RequestFilterAboutToken extends OncePerRequestFilter{

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AntPathMatcher pathMatcher; // 直接注入AntPathMatcher

    private static final String[] EXCLUDE_PATHS = {
            "/register/**",
            "/login/**",
            "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**"
            // 其他需要排除的路径模式
    };


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 获取请求的URI
        String requestURI = request.getRequestURI();

        for (String excludePath : EXCLUDE_PATHS) {
            if (pathMatcher.match(excludePath, requestURI)) {
                filterChain.doFilter(request, response);
                return;
            }
        }

        String token = request.getHeader("Token");
        //将token存入redis中
        if (token.equals("1")) {
            stringRedisTemplate.opsForValue().set(token,"1",30, TimeUnit.MINUTES);
        }
        else if (token != null && stringRedisTemplate.opsForValue().get(token) != null) {
            stringRedisTemplate.expire(token, 30, TimeUnit.MINUTES);
            filterChain.doFilter(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }


    }
}